<template>
  <div class="borrow-view">
    <h1 class="page-title">
      <Icon icon="lucide:refresh-cw" width="28" height="28" />
      借阅记录
    </h1>

    <el-card class="card-container">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="我的借阅" name="my">
          <el-table
            :data="borrowRecords"
            stripe
            v-loading="loading"
          >
            <el-table-column type="index" label="序号" width="80" align="center" />

            <el-table-column prop="bookTitle" label="书籍标题" min-width="200">
              <template #default="{ row }">
                <div style="display: flex; flex-direction: column;">
                  <span style="font-weight: 500;">{{ row.bookTitle }}</span>
                  <span style="color: #909399; font-size: 12px;">{{ row.bookAuthor }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="borrowDate" label="借阅日期" width="180" />

            <el-table-column prop="dueDate" label="预计归还日期" width="180" />

            <el-table-column prop="returnDate" label="实际归还日期" width="180">
              <template #default="{ row }">
                <span v-if="row.returnDate">{{ row.returnDate }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="状态" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)">
                  {{ getStatusName(row.status) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="120" align="center">
              <template #default="{ row }">
                <el-button
                  v-if="row.status === 'BORROWED'"
                  size="small"
                  type="success"
                  @click="handleReturn(row)"
                >
                  归还
                </el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane v-if="userRole === 'ADMIN'" label="全部记录" name="all">
          <div style="margin-bottom: 16px; display: flex; gap: 12px;">
            <el-input
              v-model="searchUserId"
              placeholder="请输入用户ID"
              style="width: 200px;"
              clearable
            />
            <el-button type="primary" @click="loadAllBorrowRecords">搜索</el-button>
          </div>

          <el-table
            :data="allBorrowRecords"
            stripe
            v-loading="loadingAll"
          >
            <el-table-column type="index" label="序号" width="80" align="center" />

            <el-table-column prop="username" label="用户名" width="120" />

            <el-table-column prop="bookTitle" label="书籍标题" min-width="200">
              <template #default="{ row }">
                <div style="display: flex; flex-direction: column;">
                  <span style="font-weight: 500;">{{ row.bookTitle }}</span>
                  <span style="color: #909399; font-size: 12px;">{{ row.bookAuthor }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="borrowDate" label="借阅日期" width="180" />

            <el-table-column prop="dueDate" label="预计归还日期" width="180" />

            <el-table-column prop="returnDate" label="实际归还日期" width="180">
              <template #default="{ row }">
                <span v-if="row.returnDate">{{ row.returnDate }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="状态" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)">
                  {{ getStatusName(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@iconify/vue'
import { useAuthStore } from '@/store/auth'
import {
  getMyBorrowRecords,
  getBorrowRecords,
  returnBook
} from '@/api/borrow'

const authStore = useAuthStore()
const userRole = computed(() => authStore.user?.role)

const activeTab = ref('my')
const loading = ref(false)
const loadingAll = ref(false)
const borrowRecords = ref([])
const allBorrowRecords = ref([])
const searchUserId = ref('')

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const loadMyBorrowRecords = async () => {
  loading.value = true
  try {
    const response = await getMyBorrowRecords({
      current: pagination.current,
      size: pagination.size
    })

    if (response.data.code === 200) {
      borrowRecords.value = response.data.data.records
      pagination.total = response.data.data.total
    }
  } catch (error) {
    console.error('加载借阅记录失败:', error)
  } finally {
    loading.value = false
  }
}

const loadAllBorrowRecords = async () => {
  loadingAll.value = true
  try {
    const response = await getBorrowRecords({
      current: pagination.current,
      size: pagination.size,
      userId: searchUserId.value || null
    })

    if (response.data.code === 200) {
      allBorrowRecords.value = response.data.data.records
      pagination.total = response.data.data.total
    }
  } catch (error) {
    console.error('加载全部借阅记录失败:', error)
  } finally {
    loadingAll.value = false
  }
}

const handleTabChange = (tab) => {
  pagination.current = 1
  if (tab === 'my') {
    loadMyBorrowRecords()
  } else {
    loadAllBorrowRecords()
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  if (activeTab.value === 'my') {
    loadMyBorrowRecords()
  } else {
    loadAllBorrowRecords()
  }
}

const handleCurrentChange = (current) => {
  pagination.current = current
  if (activeTab.value === 'my') {
    loadMyBorrowRecords()
  } else {
    loadAllBorrowRecords()
  }
}

const handleReturn = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要归还《${row.bookTitle}》吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await returnBook(row.id)
    ElMessage.success('归还成功')
    loadMyBorrowRecords()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '归还失败')
    }
  }
}

const getStatusName = (status) => {
  const map = {
    'BORROWED': '借阅中',
    'RETURNED': '已归还',
    'OVERDUE': '逾期'
  }
  return map[status] || status
}

const getStatusTagType = (status) => {
  const map = {
    'BORROWED': 'primary',
    'RETURNED': 'success',
    'OVERDUE': 'danger'
  }
  return map[status] || 'info'
}

onMounted(() => {
  loadMyBorrowRecords()
})
</script>

<style scoped>
.borrow-view {
  padding: 0;
}
</style>
